﻿using Microsoft.AspNetCore.Mvc;
using Nasty.Core.Authorization;
using Nasty.Core.LoadParams;
using Nasty.Core.Model;
using Nasty.Core.Registry;
using Nasty.Core.Session;
using Nasty.Core.Entity.System;
using Nasty.Core.SuperExtension;
using SqlSugar;
using System.Security.Principal;

namespace Nasty.Core.Service
{
    public interface ISerialNumberService : IAutofacRegister
    {
        public ResultData<string> Generate(string code);
    }

    public class SerialNumberService : ISerialNumberService
    {
        public required SqlSugarClient DbClient { get; set; }

        public ResultData<string> Generate(string code)
        {
            // 启用事务
            return DbClient.Ado.UseTran(() =>
            {
                // 查询并加行锁
                var config = DbClient.Queryable<SerialNumberConfig>()
                    .Where(t => t.Code == code)
                    .First();

                if (config == null) return ResultHelper<string>.Error("配置不能为空");

                //得到config 再进行悲观锁等待模式，避免并发问题
                config = DbClient.Queryable<SerialNumberConfig>()
                    .TranLock(DbLockType.Wait)
                    .InSingle(config.Id);

                var prefix = config.Prefix ?? string.Empty;
                var timeFormat = config.TimeFormat ?? "yyyyMMdd";
                var autoIncrementLength = config.AutoIncrementLength;
                var currentIncrement = config.CurrentIncrement;

                var timePart = DateTime.Now.ToString(timeFormat);
                var incrementPart = autoIncrementLength > 0 ? (currentIncrement + 1).ToString().PadLeft(autoIncrementLength, '0') : "";
                var serialNumber = $"{prefix}{timePart}{incrementPart}";

                // 更新当前自增值
                if (autoIncrementLength > 0) config.CurrentIncrement = currentIncrement + 1;
                DbClient.Update(config);

                return ResultHelper<string>.Success(serialNumber);
            }).Data!;
        }
    }
}
